const express = require('express');
const cors = require('cors');
const fileRoutes = require('./routes/files');
const ashoreRoutes = require('./routes/ashore');
const positionRoutes = require('./routes/positionRoutes');
const scoreRoutes = require('./routes/scoreRoutes');
const { connectToDatabase, closeDatabaseConnection } = require('./db/mongooseConnection'); // 更新路径

const app = express();
const PORT = process.env.PORT || 3000;
// 配置跨域
app.use(cors({
  origin: '*',          // 允许所有来源访问，可以改成指定域名如 "http://localhost:8080"
  methods: ['GET','POST','PUT','DELETE','OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization']
}));

// 中间件
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 路由
app.use('/files', fileRoutes);
app.use('/ashore', ashoreRoutes); // 新增
app.use('/positions', positionRoutes);
app.use('/scores', scoreRoutes);

// 启动服务器
const server = app.listen(PORT, async () => {
  console.log(`服务器运行在端口 ${PORT}`);
  
  // 启动时连接到数据库
  try {
    await connectToDatabase();
    console.log('数据库连接已建立');
  } catch (error) {
    console.error('启动时连接数据库失败:', error);
  }
});

// 优雅关闭
process.on('SIGINT', async () => {
  console.log('正在关闭服务器...');
  await closeDatabaseConnection();
  server.close(() => {
    console.log('服务器已关闭');
    process.exit(0);
  });
});

process.on('SIGTERM', async () => {
  console.log('正在关闭服务器...');
  await closeDatabaseConnection();
  server.close(() => {
    console.log('服务器已关闭');
    process.exit(0);
  });
});